<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="用户id" prop="userId">
              <el-input v-model="queryParams.userId" placeholder="请输入用户id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="序号" prop="mark">
              <el-input v-model="queryParams.mark" placeholder="请输入序号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="订单编号" prop="orderSn">
              <el-input v-model="queryParams.orderSn" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择类型" clearable >
                <el-option v-for="dict in biz_found_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="提现金额" prop="amount">
              <el-input v-model="queryParams.amount" placeholder="请输入提现金额" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="手续费" prop="feeAmount">
              <el-input v-model="queryParams.feeAmount" placeholder="请输入手续费" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="实际到账" prop="actualAmount">
              <el-input v-model="queryParams.actualAmount" placeholder="请输入实际到账金额" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="hash" prop="txHash">
              <el-input v-model="queryParams.txHash" placeholder="请输入hash" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in biz_audit_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间" prop="transferTime">
              <el-date-picker clearable v-model="queryParams.transferTime" type="daterange" value-format="YYYY-MM-DD"
                placeholder="请选择时间" style="width: 240px;" />
            </el-form-item>
            <el-form-item label="提现地址" prop="fromAddress">
              <el-input v-model="queryParams.fromAddress" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['business:userWithdrawal:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['business:userWithdrawal:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['business:userWithdrawal:remove']">删除</el-button>
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['business:userWithdrawal:export']">导出</el-button>
          </el-col>
          <el-col :span="50">
            <div class="statistics">
              <span style="color: red">USDT总金额: {{ statistics.usdtAmount }}</span>
              <span style="color: red">USDT手续费: {{ statistics.usdtFeeAmount }}</span>
              <span style="color: red">USDT实际到账: {{ statistics.usdtActualAmount }}</span>
              <span style="color: green">ALEO总金额: {{ statistics.aleoAmount }}</span>
              <span style="color: green">ALEO手续费: {{ statistics.aleoFeeAmount }}</span>
              <span style="color: green">ALEO实际到账: {{ statistics.aleoActualAmount }}</span>
              <span style="color: black">SCR总金额: {{ statistics.scrAmount }}</span>
              <span style="color: black">SCR手续费: {{ statistics.scrFeeAmount }}</span>
              <span style="color: black">SCR实际到账: {{ statistics.scrActualAmount }}</span>
            </div>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="userWithdrawalList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="true" show-overflow-tooltip />
        <el-table-column label="用户id" align="center" prop="userId" />
        <el-table-column label="序号" align="center" prop="mark" />
        <el-table-column label="是否新用户" align="center" prop="isNew" width="100">
          <template #default="scope">
            <div>
              {{scope.row.isNew ? '新用户' : '老用户'}}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="biz_found_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="订单编号" align="center" prop="orderSn" width="200" show-overflow-tooltip />
        <el-table-column label="提现金额" align="center" prop="amount" width="150" />
        <el-table-column label="手续费" align="center" prop="feeAmount" width="150" />
        <el-table-column label="实际到账金额" align="center" prop="actualAmount" width="150" />
        <el-table-column label="hash" align="center" prop="txHash" width="200" show-overflow-tooltip />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="biz_audit_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="提现地址" align="center" prop="fromAddress" width="500" show-overflow-tooltip>
          <template #default="scope">
            <div style="display: flex;align-items: center;justify-content: center;cursor: pointer;"
              @click="copy(scope.row.fromAddress)">
              {{ scope.row.fromAddress }}
              <el-icon style="margin-left: 5px;">
                <CopyDocument />
              </el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="链上详情" align="center" prop="notifyData" width="200" show-overflow-tooltip />
        <el-table-column label="备注" align="center" prop="remark" width="150" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150">
          <template #default="scope">
            <el-tooltip content="审核" placement="top" v-if="scope.row.status == 1">
              <el-button link type="primary" @click="handleWithDraw(scope.row)"
                v-hasPermi="['business:user:handleWithDraw']">审核</el-button>
            </el-tooltip>
            
            <el-tooltip content="查询状态" placement="top"
              v-if="scope.row.txHash && scope.row.status == 2 && scope.row.type == 3">
              <el-button link type="primary" @click="queryAleoStatus(scope.row, scope.row.txHash)"
                v-hasPermi="['business:user:queryAleoStatus']">查询状态</el-button>
            </el-tooltip>
            <el-tooltip content="查询状态" placement="top"
              v-if="scope.row.txHash && scope.row.status == 2 && scope.row.type == 10">
              <el-button link type="primary" @click="getScrOrderStatus(scope.row, scope.row.txHash)"
                v-hasPermi="['business:user:queryAleoStatus']">查询状态</el-button>
            </el-tooltip>
            <el-tooltip content="完成" placement="top" v-if="scope.row.status == 2 || scope.row.status == 1">
              <el-button link type="success" @click="handleSuccess(scope.row)"
                v-hasPermi="['business:user:handleSuccess']">完成</el-button>
            </el-tooltip>
            <!-- <el-tooltip content="拒绝" placement="top">
              <el-button link type="primary" @click="handleDelete(scope.row)"
                v-hasPermi="['business:userWithdrawal:remove']">拒绝</el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改用户提现记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="userWithdrawalFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderSn">
          <el-input v-model="form.orderSn" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="提现金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入提现金额" />
        </el-form-item>
        <el-form-item label="手续费" prop="feeAmount">
          <el-input v-model="form.feeAmount" placeholder="请输入手续费" />
        </el-form-item>
        <el-form-item label="实际到账金额" prop="actualAmount">
          <el-input v-model="form.actualAmount" placeholder="请输入实际到账金额" />
        </el-form-item>
        <el-form-item label="hash" prop="txHash">
          <el-input v-model="form.txHash" placeholder="请输入hash" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in biz_audit_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间" prop="transferTime">
          <el-date-picker clearable v-model="form.transferTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="" prop="fromAddress">
          <el-input v-model="form.fromAddress" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="数据" prop="notifyData">
          <el-input v-model="form.notifyData" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserWithdrawal" lang="ts">
  import { listUserWithdrawal, getUserWithdrawal, delUserWithdrawal, addUserWithdrawal, updateUserWithdrawal, queryWithdrawalData } from '@/api/business/userWithdrawal';
  import { UserWithdrawalVO, UserWithdrawalQuery, UserWithdrawalForm } from '@/api/business/userWithdrawal/types';
  import Web3 from 'web3';
  import detectEthereumProvider from '@metamask/detect-provider'

  import useClipboard from "vue-clipboard3";
  /** 数据初始化定义 */
  const { toClipboard } = useClipboard();

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { biz_audit_status, biz_found_type } = toRefs<any>(proxy?.useDict('biz_audit_status', 'biz_found_type'));

  const userWithdrawalList = ref<UserWithdrawalVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);

  const queryFormRef = ref<ElFormInstance>();
  const userWithdrawalFormRef = ref<ElFormInstance>();

  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  const initFormData : UserWithdrawalForm = {
    id: undefined,
    userId: undefined,
    type: undefined,
    mark: undefined,
    orderSn: undefined,
    amount: undefined,
    feeAmount: undefined,
    actualAmount: undefined,
    txHash: undefined,
    status: undefined,
    transferTime: undefined,
    fromAddress: undefined,
    notifyData: undefined,
    remark: undefined,
  }
  const data = reactive<PageData<UserWithdrawalForm, UserWithdrawalQuery>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      userId: undefined,
      mark: undefined,
      type: undefined,
      orderSn: undefined,
      amount: undefined,
      feeAmount: undefined,
      actualAmount: undefined,
      txHash: undefined,
      status: undefined,
      transferTime: undefined,
      fromAddress: undefined,
      notifyData: undefined,
      params: {}
    },
    rules: {
      id: [
        { required: true, message: "主键不能为空", trigger: "blur" }
      ],
      userId: [
        { required: true, message: "用户id不能为空", trigger: "blur" }
      ],
      type: [
        { required: true, message: "类型不能为空", trigger: "change" }
      ],
      orderSn: [
        { required: true, message: "订单编号不能为空", trigger: "blur" }
      ],
      amount: [
        { required: true, message: "提现金额不能为空", trigger: "blur" }
      ],
      feeAmount: [
        { required: true, message: "手续费不能为空", trigger: "blur" }
      ],
      actualAmount: [
        { required: true, message: "实际到账金额不能为空", trigger: "blur" }
      ],
      txHash: [
        { required: true, message: "hash不能为空", trigger: "blur" }
      ],
      status: [
        { required: true, message: "状态不能为空", trigger: "change" }
      ],
      transferTime: [
        { required: true, message: "时间不能为空", trigger: "blur" }
      ],
      fromAddress: [
        { required: true, message: "不能为空", trigger: "blur" }
      ],
      notifyData: [
        { required: true, message: "数据不能为空", trigger: "blur" }
      ],
      remark: [
        { required: true, message: "备注不能为空", trigger: "blur" }
      ],
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  const statistics = reactive({
    usdtAmount: 0,
    usdtFeeAmount: 0,
    usdtActualAmount: 0,
    aleoAmount: 0,
    aleoFeeAmount: 0,
    aleoActualAmount: 0,
    scrAmount: 0,
    scrFeeAmount: 0,
    scrActualAmount: 0
  });

  const getStatistics = async () => {
    let startTime = null, endTime = null;
    if (queryParams.value.transferTime) {
      startTime = queryParams.value.transferTime[0] + ' 00:00:00';
      endTime = queryParams.value.transferTime[1] + ' 23:59:59';
    }
    let queryParamsClone = JSON.parse(JSON.stringify(queryParams.value));
    delete queryParamsClone['transferTime'];
    const res = await queryWithdrawalData({
      ...queryParamsClone,
      startTime,
      endTime
    });
    Object.assign(statistics, res.data);
  };

  /** 查询用户提现记录列表 */
  const getList = async () => {
    loading.value = true;
    let startTime = null, endTime = null
    if (queryParams.value.transferTime) {
      startTime = queryParams.value.transferTime[0] + ' 00:00:00'
      endTime = queryParams.value.transferTime[1] + ' 23:59:59'
      // queryParams.value.transferTime = null
    }
    let queryParamsClone = JSON.parse(JSON.stringify(queryParams.value))
    delete queryParamsClone['transferTime']
    const res = await listUserWithdrawal({
      ...queryParamsClone,
      startTime,
      endTime
    });
    userWithdrawalList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  }

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  }

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    userWithdrawalFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
    getStatistics();
  }

  /** 重置按钮操作 */
  const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
  }

  /** 多选框选中数据 */
  const handleSelectionChange = (selection : UserWithdrawalVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加用户提现记录";
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: UserWithdrawalVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getUserWithdrawal(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.title = "修改用户提现记录";
  }

  /** 提交按钮 */
  const submitForm = () => {
    userWithdrawalFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateUserWithdrawal(form.value).finally(() => buttonLoading.value = false);
        } else {
          await addUserWithdrawal(form.value).finally(() => buttonLoading.value = false);
        }
        proxy?.$modal.msgSuccess("操作成功");
        dialog.visible = false;
        await getList();
      }
    });
  }

  /** 删除按钮操作 */
  const handleDelete = async (row ?: UserWithdrawalVO) => {
    const _ids = row?.id || ids.value;
    await proxy?.$modal.confirm('是否确认删除用户提现记录编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
    await delUserWithdrawal(_ids);
    proxy?.$modal.msgSuccess("删除成功");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download('business/userWithdrawal/export', {
      ...queryParams.value
    }, `userWithdrawal_${new Date().getTime()}.xlsx`)
  }
  // 提现
  const handleWithDraw = async (row ?: any) => {

    ElMessageBox.confirm(
      '确认该笔提现申请， 是否同意?',
      '提现提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '拒绝',
        type: 'warning',
        distinguishCancelAndClose: true,
      }
    )
      .then(async (result) => {
        console.log(result)
        if (row.type == 3) {
          aleoTransaction(row, row.fromAddress, row.actualAmount)
        } else if (row.type == 10) {
          scrTransaction(row, row.fromAddress, row.actualAmount)
        } else if (row.type == 2) {
          usdtTransaction(row, row.fromAddress, row.actualAmount)
        }
      })
      .catch((err) => {
        console.log(err)
        if (err == 'cancel') {
          // 拒绝
          doSuccess(row, row.txHash, 5)
        }
      })

  }
  // 成功
  const handleSuccess = async (row ?: any) => {

    ElMessageBox.confirm(
      '确认完成该笔提现申请， 确认?',
      '完成提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(async () => {
        doSuccess(row, row.txHash, 3)
      })
      .catch(() => {
        // ElMessage({
        //   type: 'info',
        //   message: 'Delete canceled',
        // })
      })

  }
  // 成功
  const doSuccess = async (row ?: any, txHash : any, status = 2) => {

    let params = status == 2 ? {
      id: row.id,
      type: row.type,
      status,
      txHash
    } : {
      id: row.id,
      type: row.type,
      status
    }

    await updateUserWithdrawal(params).finally(async () => {
      console.log('成功')
      proxy?.$modal.msgSuccess("提现成功");
      await getList();
    });
  }

  const provider = ref(null)
  const getProvider = () => {
    const provider = window.foxwallet && window.foxwallet.aleo;
    if (!provider) {
      window.open("https://foxwallet.com/download");
      throw `Please guide users to download from FoxWallet official website`;
    }
    return provider;
  }

  const aleoTransaction = async (row ?: any, transferAddress : any, amount : any) => {
    try {
      provider.value = getProvider()
      provider.value.on("connect", async (address) => {
        console.log(address)
      })
    } catch (e) {
      console.log('connect failed', e);
    }
    const address = await provider.value.connect("ON_CHAIN_HISTORY", "mainnet");
    console.log("connected address ", address);
    if (address) {
      try {
        const result = await provider.value.requestTransaction({
          // address: "aleo14jkq429nscxwvk07wlfdhprz788s56wp4wk0rcrtlj6nu4fh0c8q004h35",
          // "aleo17zzj9e8rlmg2s7jdhjayj0k08r92cdvauggakpp8jg6p3eqax5ysharzea"
          // "aleo17q7z5m9a4wg46xd0srg5a4dfftsyhw0ajkm8syqvupdqfvr6tvgsgwpquy"
          chainId: "mainnet",
          transitions: [
            {

              program: "credits.aleo",
              functionName: "transfer_public",
              inputs: [transferAddress /* transfer address */, amount * 1000000 + 'u64']
            }
          ],
          fee: 65_000  /* estimate fee */,
          feePrivate: false
        });
        console.log("requestTransaction ", result);

        doSuccess(row, result.transactionId)

      } catch (e) {
        console.log('requestTransaction failed', e);
      }
    }
  }

  const usdtTransaction = async (row ?: any, transferAddress : any, count : any) => {
    if (typeof window.ethereum.isTokenPocket !== 'undefined') {
      const res = await ethereum.request({ method: 'eth_requestAccounts' });
    }
    const provider = await detectEthereumProvider();
    if (!provider) {
      const provider = window.bitkeep && window.bitkeep.ethereum;
      alert('Please install MetaMask to continue.');
      return;
    }
    const web3 = new Web3(provider);
    
    const usdtAbi = [{
      "inputs": [],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "constructor"
    }, {
      "anonymous": false,
      "inputs": [{
        "indexed": true,
        "internalType": "address",
        "name": "owner",
        "type": "address"
      }, {
        "indexed": true,
        "internalType": "address",
        "name": "spender",
        "type": "address"
      }, {
        "indexed": false,
        "internalType": "uint256",
        "name": "value",
        "type": "uint256"
      }],
      "name": "Approval",
      "type": "event"
    }, {
      "anonymous": false,
      "inputs": [{
        "indexed": true,
        "internalType": "address",
        "name": "previousOwner",
        "type": "address"
      }, {
        "indexed": true,
        "internalType": "address",
        "name": "newOwner",
        "type": "address"
      }],
      "name": "OwnershipTransferred",
      "type": "event"
    }, {
      "anonymous": false,
      "inputs": [{
        "indexed": true,
        "internalType": "address",
        "name": "from",
        "type": "address"
      }, {
        "indexed": true,
        "internalType": "address",
        "name": "to",
        "type": "address"
      }, {
        "indexed": false,
        "internalType": "uint256",
        "name": "value",
        "type": "uint256"
      }],
      "name": "Transfer",
      "type": "event"
    }, {
      "constant": true,
      "inputs": [],
      "name": "_decimals",
      "outputs": [{
        "internalType": "uint8",
        "name": "",
        "type": "uint8"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": true,
      "inputs": [],
      "name": "_name",
      "outputs": [{
        "internalType": "string",
        "name": "",
        "type": "string"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": true,
      "inputs": [],
      "name": "_symbol",
      "outputs": [{
        "internalType": "string",
        "name": "",
        "type": "string"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": true,
      "inputs": [{
        "internalType": "address",
        "name": "owner",
        "type": "address"
      }, {
        "internalType": "address",
        "name": "spender",
        "type": "address"
      }],
      "name": "allowance",
      "outputs": [{
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": false,
      "inputs": [{
        "internalType": "address",
        "name": "spender",
        "type": "address"
      }, {
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      }],
      "name": "approve",
      "outputs": [{
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    }, {
      "constant": true,
      "inputs": [{
        "internalType": "address",
        "name": "account",
        "type": "address"
      }],
      "name": "balanceOf",
      "outputs": [{
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": false,
      "inputs": [{
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      }],
      "name": "burn",
      "outputs": [{
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    }, {
      "constant": true,
      "inputs": [],
      "name": "decimals",
      "outputs": [{
        "internalType": "uint8",
        "name": "",
        "type": "uint8"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": false,
      "inputs": [{
        "internalType": "address",
        "name": "spender",
        "type": "address"
      }, {
        "internalType": "uint256",
        "name": "subtractedValue",
        "type": "uint256"
      }],
      "name": "decreaseAllowance",
      "outputs": [{
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    }, {
      "constant": true,
      "inputs": [],
      "name": "getOwner",
      "outputs": [{
        "internalType": "address",
        "name": "",
        "type": "address"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": false,
      "inputs": [{
        "internalType": "address",
        "name": "spender",
        "type": "address"
      }, {
        "internalType": "uint256",
        "name": "addedValue",
        "type": "uint256"
      }],
      "name": "increaseAllowance",
      "outputs": [{
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    }, {
      "constant": false,
      "inputs": [{
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      }],
      "name": "mint",
      "outputs": [{
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    }, {
      "constant": true,
      "inputs": [],
      "name": "name",
      "outputs": [{
        "internalType": "string",
        "name": "",
        "type": "string"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": true,
      "inputs": [],
      "name": "owner",
      "outputs": [{
        "internalType": "address",
        "name": "",
        "type": "address"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": false,
      "inputs": [],
      "name": "renounceOwnership",
      "outputs": [],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    }, {
      "constant": true,
      "inputs": [],
      "name": "symbol",
      "outputs": [{
        "internalType": "string",
        "name": "",
        "type": "string"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": true,
      "inputs": [],
      "name": "totalSupply",
      "outputs": [{
        "internalType": "uint256",
        "name": "",
        "type": "uint256"
      }],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    }, {
      "constant": false,
      "inputs": [{
        "internalType": "address",
        "name": "recipient",
        "type": "address"
      }, {
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      }],
      "name": "transfer",
      "outputs": [{
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    }, {
      "constant": false,
      "inputs": [{
        "internalType": "address",
        "name": "sender",
        "type": "address"
      }, {
        "internalType": "address",
        "name": "recipient",
        "type": "address"
      }, {
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      }],
      "name": "transferFrom",
      "outputs": [{
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    }, {
      "constant": false,
      "inputs": [{
        "internalType": "address",
        "name": "newOwner",
        "type": "address"
      }],
      "name": "transferOwnership",
      "outputs": [],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    }]
    let ArbUsdtAddress = "0x55d398326f99059ff775485246999027b3197955"
    var myContract = new web3.eth.Contract(usdtAbi, ArbUsdtAddress);
    let toAddress = transferAddress; //收款地址
    let amount = web3.utils.toWei(Number(count), 'ether')
    
    if (provider.chainId !== '0x38') {
      // 切换网络
      await ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: `0x38` }]
      })
      .then(res => {
        myContract.methods.transfer(toAddress, Math.floor(amount)).send({
          from: window.ethereum.selectedAddress
        }, (err, res) => {
          console.log(err, res)
          if (!err) {
            console.log('转账hash', res)
          } else {
            console.log('转账失败')
          }
        }).then(result => {
          console.log('转账结束', result.transactionHash)
          doSuccess(row, result.transactionHash)
        }).catch(error => {
          let logcode = error.code;
          switch (logcode) {
            case 4001:
              console.log('User Rejected transaction');
              break;
            case -32603:
              console.log('Intrinsic gas too low');
              break;
            default:
          }
        })
      });
    } else {
      myContract.methods.transfer(toAddress, Math.floor(amount)).send({
        from: window.ethereum.selectedAddress
      }, (err, res) => {
        console.log(err, res)
        if (!err) {
          console.log('转账hash', res)
        } else {
          console.log('转账失败')
        }
      }).then(result => {
        console.log('转账结束', result.transactionHash)
        doSuccess(row, result.transactionHash)
      }).catch(error => {
        let logcode = error.code;
        switch (logcode) {
          case 4001:
            console.log('User Rejected transaction');
            break;
          case -32603:
            console.log('Intrinsic gas too low');
            break;
          default:
        }
      })
    }
  }

  const scrTransaction = async (row ?: any, transferAddress : any, count : any, res = {}) => {
    if (typeof window.ethereum.isTokenPocket !== 'undefined') {
      const res = await ethereum.request({ method: 'eth_requestAccounts' });
    }
    const provider = await detectEthereumProvider();
    if (!provider) {
      const provider = window.bitkeep && window.bitkeep.ethereum;
      alert('Please install MetaMask to continue.');
      return;
    }
    const web3 = new Web3(provider);
    
    let { // 0x74aeff84ad35fbfb03d656ccc4d153349b11e75d  0x94F7283d73A4c42D685390b83AF6bb9788D0f207
        from = window.ethereum.selectedAddress, // 付款地址
        to = transferAddress, // 收款地址
        tokenURl = "0xd29687c813D741E2F938F4aC377128810E217b1b", // 合约地址
        value = 0,
        gas = "50000",
        nonce = 0,
        money = count, // 合约币数量
      } = res;
    const addPreZero = (num) => {
      let t = (num + "").length,
        s = "";
      for (let i = 0; i < 64 - t; i++) {
        s += "0";
      }
      return s + num;
    };
    let code = `0xa9059cbb${addPreZero(to.substring(2))}${addPreZero(
          web3.utils
            .fromDecimal(web3.utils.toWei(money, "ether"))
            .substring(2)
        )}`;
    
    
    if (provider.chainId !== '0x82750') {
      // 切换网络
      await ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: `0x82750` }]
      })
      .then(res => {
        ethereum.request({
            method: 'eth_sendTransaction',
              params: [
                    {
                      to: tokenURl,
                      from,
                      chainId: '0x82750',
                      data: code
                    },
                  ],
          })
          .then((txHash) => {
            doSuccess(row, txHash)
          })
          .catch((error) => console.error);
      });
    } else {
      ethereum.request({
          method: 'eth_sendTransaction',
            params: [
                  {
                    to: tokenURl,
                    from,
                    chainId: '0x82750',
                    data: code
                  },
                ],
        })
        .then((txHash) => {
          doSuccess(row, txHash)
        })
        .catch((error) => console.error);
    }
  }
  // 查询aleo订单状态
  const queryAleoStatus = async (row : any, transaction_id : any) => {
    provider.value = getProvider()
    const address = await provider.value.connect("ON_CHAIN_HISTORY", "mainnet");
    if (address) {
      try {
        const result = await provider.value.transactionStatus(transaction_id);
        // type Status = "Queued" | "Generating Prover Files" | "Generating Transaction" | "Broadcasting" | "Completed" | "Rejected" | "Finalized" | "Failed"
        console.log("transactionStatus ", result);
        if (result.status == "Finalized") {
          ElMessage.success("Aleo交易成功");
          // 完成
          doSuccess(row, row.txHash, 3)
        } else if (result.status == "Failed" || result.status == "Rejected") {
          ElMessage.error("Aleo交易失败");
        } else {
          ElMessage.info("Aleo交易进行中...");
        }
      } catch (e) {
        ElMessage.error("查询Aleo交易失败");
        console.log('transactionStatus failed', e);
      }
    }
  }
  
  // 查询scr状态
  async function getScrOrderStatus(row : any, orderHash : any) {
    try {
      const txReceipt = await ethereum.request({
        method: 'eth_getTransactionReceipt',
        params: [orderHash]
      });
      if (txReceipt === null) {
          ElMessage.info("SCR转账交易尚未被网络确认...");
          console.log("转账交易尚未被网络确认。");
            // 如果txReceipt为null，表示交易尚未被网络确认。
            // 可以继续查询或者给用户提示等待
      } else {
        console.log("转账交易已被网络确认。");
        // 如果txReceipt不为null，表示交易已被网络确认。
        // 可以根据txReceipt.status判断转账是否成功
        if (txReceipt.status === true || txReceipt.status === '0x1') {
          ElMessage.success("SCR交易成功");
          // 完成
          doSuccess(row, orderHash, 3)
          console.log("转账成功。");
          // 转账操作已完成且成功
        } else {
          ElMessage.error("SCR交易失败");
          console.log("转账失败。");
          // 转账操作已完成但失败
        }
      }
    } catch (error) {
      console.error('Error fetching order status:', error);
      return null;
    }
  }
  
  const copy = async (address: any) => {
    // navigator.clipboard.writeText(address);
    // 如果clipboard API失败，可以回退到使用document.execCommand()方法
    try {
        await navigator.clipboard.writeText(address);
        ElMessage.success("复制成功");
    } catch (err) {
        console.error('复制失败', err);
        // 如果clipboard API失败，可以回退到使用document.execCommand()方法
        copyContent2(address);
    }
  }
  
  // 复制文本内容方法二
  const copyContent2 = (text: any) => {
      // 复制结果
      let copyResult = true
      // 创建一个input元素
      let inputDom = document.createElement('textarea');
      // 设置为只读 防止移动端手机上弹出软键盘  
      inputDom.setAttribute('readonly', 'readonly');
      // 给input元素赋值
      inputDom.value = text;
      // 将创建的input添加到body
      document.body.appendChild(inputDom);
      // 选中input元素的内容
      inputDom.select();
      // 执行浏览器复制命令
      // 复制命令会将当前选中的内容复制到剪切板中（这里就是创建的input标签中的内容）
      // Input要在正常的编辑状态下原生复制方法才会生效
      const result = document.execCommand('copy')
      // 判断是否复制成功
      if (result) {
        ElMessage.success("复制成功");
      } else {
        console.log('复制失败');
        copyResult = false
      }
      // 复制操作后再将构造的标签 移除
      document.body.removeChild(inputDom);
      // 返回复制操作的最终结果
      return copyResult;
  }
  onMounted(async () => {
    console.log(window)
    var isFoxWallet = !!window.foxwallet;
    console.log(isFoxWallet)
    getList();
    getStatistics();
  });

  watch(queryParams, () => {
    getStatistics();
  });
</script>

<style>
.statistics {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  font-size: 15px;
}
</style>